package com.bizihang.common.security.core.code.email;


import com.bizihang.common.security.core.SecurityConstants;
import com.bizihang.common.security.core.code.AbstractValidateCodeGenerator;
import com.bizihang.common.security.core.code.ValidateCode;
import com.bizihang.common.security.core.properties.code.EmailCodeProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Arrays;

/**
 * 短信验证码生成器
 *
 * @author 毕子航 951755883@qq.com
 * @date 2018/10/19
 */
@Slf4j
@Component("emailValidateCodeGenerator")
public class EmailCodeGenerator extends AbstractValidateCodeGenerator {
	public static final String ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE = "请求缺少email参数";

	/**
	 * 从http请求中获取email参数，从securityProperties获取email验证码的过期时间间隔
	 *
	 * @param request the request
	 * @return 生成校验码对象
	 */
	@Override
	public ValidateCode generate(ServletWebRequest request) {
		EmailCodeProperties email = super.getSecurityProperties().getCode().getEmail();
		try {
			String[] emails = ServletRequestUtils.getRequiredStringParameters(request.getRequest(), SecurityConstants.DEFAULT_PARAMETER_NAME_EMAIL);
			log.info(Arrays.toString(emails));
			String code = Arrays.toString(emails);
			return new ValidateCode(code, email.getExpireIn());
		} catch (ServletRequestBindingException e) {
			if (log.isDebugEnabled()) {
				e.printStackTrace();
			}
			throw new IllegalArgumentException(ILLEGAL_ARGUMENT_EXCEPTION_MESSAGE);
		}
	}
}
